package com.davy.gridpoint.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatButton;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.davy.gridpoint.BaseActivity;
import com.davy.gridpoint.DavyApp;
import com.davy.gridpoint.R;
import com.davy.gridpoint.ScreenManager;
import com.davy.gridpoint.adapter.MainAdapter;
import com.davy.gridpoint.http.CommonHttpConsts;
import com.davy.gridpoint.http.HttpCallbackData;
import com.davy.gridpoint.http.HttpClient;
import com.davy.gridpoint.http.JsonBeanData;
import com.davy.gridpoint.utils.DeviceIdHelper;
import com.davy.gridpoint.utils.DialogUitl;
import com.davy.gridpoint.utils.LogUtils;
import com.davy.gridpoint.utils.SPUtils;
import com.davy.gridpoint.utils.StringUtils;
import com.davy.gridpoint.utils.ToastUtil;
import com.davy.gridpoint.view.CustomImageView;
import com.davy.gridpoint.view.IndicatorProgressBar;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;

import java.io.File;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class MainActivity extends BaseActivity {
    private long mExitTime = 0;//退出程序
    private TextView tvTitle;
    private LinearLayout lyNoLayout;
    private RecyclerView mXRecyclerView;
    private MainAdapter mainAdapter;
    private ArrayList<Map> dataList;
    private String strSelect = "";
    private String pwsSelect = "";
    private AppCompatButton tvTakePhoto;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        statusbar4();
        strSelect = SPUtils.get(mContext, "strSelect", "") + "";
        pwsSelect = SPUtils.get(mContext, "pwsSelect", "") + "";
        LogUtils.e("TAG", "pwsSelect" + pwsSelect);
        initView();
        String insertTime = SPUtils.get(mContext, "benS", "") + "";
        if (!StringUtils.isEmpty(insertTime)) {
            upLogInfo(insertTime);
        }
        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_PERMISSION_CODE);
        } else {
            LogUtils.e("TAG", "权限已经授予");
            // 权限已经授予，可以进行位置相关的操作
            initLocation();
        }
        initClick();
    }

    private void initView() {
        dataList = new ArrayList<>();
        decimalFormat = new DecimalFormat("#.00000000");
        decimalFormat2 = new DecimalFormat("#.00");
        tvTitle = findViewById(R.id.tvTitle);
        if (!StringUtils.isEmpty(strSelect)) {
            tvTitle.setText(strSelect);
        }

        mXRecyclerView = findViewById(R.id.mXRecyclerView);
        lyNoLayout = findViewById(R.id.lyNoLayout);
        lyNoLayout.setVisibility(View.VISIBLE);
        tvTakePhoto = findViewById(R.id.tvTakePhoto);

        destfiledir = Environment.getExternalStorageDirectory().getPath();
        LogUtils.e("tag", "destfiledir:" + destfiledir);
        mProgress = findViewById(R.id.update_progress);
        rl_softu = findViewById(R.id.rl_softu);
        lyDialog = findViewById(R.id.lyDialog);
        tvContext = findViewById(R.id.tvContext);
        tvDialogCancel = findViewById(R.id.tvDialogCancel);
        tvDialogConfirm = findViewById(R.id.tvDialogConfirm);
        rl_softu.setVisibility(View.GONE);
        rl_softu.setOnClickListener(v -> {
        });
        lyDialog.setOnClickListener(v -> {
        });

        tvDialogCancel.setOnClickListener(v -> {
            tvTakePhoto.setVisibility(View.VISIBLE);
            lyDialog.setVisibility(View.GONE);
        });
        tvDialogConfirm.setOnClickListener(v -> {
            lyDialog.setVisibility(View.GONE);
            rl_softu.setVisibility(View.VISIBLE);
            downloadNewFile();
        });

        upVersions();

        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext, RecyclerView.VERTICAL, false);
        mXRecyclerView.setLayoutManager(layoutManager);
        mainAdapter = new MainAdapter(mContext, dataList);
        mXRecyclerView.setAdapter(mainAdapter);
        mainAdapter.setItemClickListener(new MainAdapter.ItemClickListener() {
            @Override
            public void onClick(int pos, Map mData) {
                if (StringUtils.isFastClick()) {
                    return;
                }
                Intent intent = new Intent(mContext, Grid2Activity.class);
                intent.putExtra("dataMap", (Serializable) mData);
                startActivity(intent);

//                if (pos == 1) {
//                    ArrayList<String> img = new Gson().fromJson(mData.get("img_path") + "", ArrayList.class);
//                    imgDialog(HttpClient.imgUrl + img.get(0));
//                }
//                if (pos == 2) {
//                    Intent intent = new Intent(mContext, WebViewActivity.class);
//                    intent.putExtra("title", "查看定位");
//                    intent.putExtra("url", "http://139.129.8.107:6011/map.html?lng=" + mData.get("longitude") + "&lat=" + mData.get("latitude"));
//                    startActivity(intent);
//                }
//                if (pos == 3) {
//                    Intent intent = new Intent(mContext, Grid2Activity.class);
//                    intent.putExtra("dataMap", (Serializable) mData);
//                    startActivity(intent);
//                }
            }

            @Override
            public void delClick(int pos, Map mData) {
                if (StringUtils.isFastClick()) {
                    return;
                }
                delDialog(mData.get("pws_id") + "", mData.get("id") + "");
            }
        });

        tvTakePhoto.setOnClickListener(v -> {
            if (StringUtils.isFastClick()) {
                return;
            }
            startActivity(new Intent(mContext, GridActivity.class));
        });

        RPCGetGridPhoto();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        strSelect = SPUtils.get(mContext, "strSelect", "") + "";
        pwsSelect = SPUtils.get(mContext, "pwsSelect", "") + "";
        if (!StringUtils.isEmpty(strSelect)) {
            tvTitle.setText(strSelect);
        }
        if (tvTakePhoto != null) {
            tvTakePhoto.setVisibility(View.VISIBLE);
        }
        RPCGetGridPhoto();
    }

    private void RPCGetGridPhoto() {
        LogUtils.e("TAG", "RPCGetGridPhoto" + pwsSelect);
        if (StringUtils.isEmpty(pwsSelect)) {
            ToastUtil.showNew(mContext, "请选择工务段");
            return;
        }

        HttpClient.getInstance().getData(CommonHttpConsts.RPCGetGridPhoto, "RPCGetGridPhoto").tag(this).params("pwsid", pwsSelect).execute(new HttpCallbackData() {

            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onSuccess(int code, String msg, String info) {
                LogUtils.e("TAG", "info:" + info);

                if (code == 200) {
                    if (!StringUtils.isEmpty(info)) {
                        String string = StringUtils.decompressForGzip(info);
                        LogUtils.e("TAG", "string:" + string);
                        dataList = (ArrayList<Map>) JSONArray.parseArray(string, Map.class);
                    }
                } else {
                    dataList.clear();
                    dataList = new ArrayList<>();
                    ToastUtil.show(msg);
                }

                mainAdapter.setData(dataList);
                if (dataList.size() > 0) {
                    mXRecyclerView.setVisibility(View.VISIBLE);
                    lyNoLayout.setVisibility(View.GONE);
                } else {
                    mXRecyclerView.setVisibility(View.GONE);
                    lyNoLayout.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public boolean showLoadingDialog() {
                return true;
            }

            @Override
            public Dialog createLoadingDialog() {
                return DialogUitl.loginAuthDialog(mContext);
            }

            @Override
            public void onError() {
                super.onError();
                ToastUtil.show(StringUtils.error_context);
            }

            @Override
            public void onFinish() {
                super.onFinish();
//                        mXRecyclerView.refreshComplete();
//                        mXRecyclerView.setPullRefreshEnabled(true);
            }
        });
    }

    public void delDialog(String pws_id, String id) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.dialog);
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.dialog_exit, null);
        TextView tvDelete = v.findViewById(R.id.tvDelete);
        TextView tvSave = v.findViewById(R.id.tvSave);
        TextView tvName = v.findViewById(R.id.tvName);
        AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);//点击屏幕不消失

        if (!dialog.isShowing()) {//此时提示框未显示
            dialog.show();
        }
        dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);

        //自定义的东西
        dialog.getWindow().setContentView(v);
        tvDelete.setOnClickListener(v1 -> dialog.dismiss());
        tvName.setText("确认删除该条数据吗");
        tvSave.setOnClickListener(view -> {
            if (StringUtils.isFastClick()) {
                return;
            }
            RPCDelGridPhoto(pws_id, id);
            dialog.dismiss();
        });
    }

    private void RPCDelGridPhoto(String pwsid, String id) {
        HttpClient.getInstance().getData(CommonHttpConsts.RPCDelGridPhoto, "RPCDelGridPhoto").tag(this).params("pwsid", pwsid).params("id", id).execute(new HttpCallbackData() {

            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onSuccess(int code, String msg, String info) {
                LogUtils.e("TAG", "info:" + info);
                ToastUtil.show(msg);
                if (code == 200) {
                    RPCGetGridPhoto();
                }
            }

            @Override
            public boolean showLoadingDialog() {
                return true;
            }

            @Override
            public Dialog createLoadingDialog() {
                return DialogUitl.loginAuthDialog(mContext);
            }

            @Override
            public void onError() {
                super.onError();
                ToastUtil.show(StringUtils.error_context);
            }
        });
    }

    public void imgDialog(String milepostStr) {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(mContext);
        android.app.AlertDialog dialog = builder.create();
        // 显示对话框前，设置全屏
        dialog.setOnShowListener(d -> {
            // 获取对话框窗口
            Window window = dialog.getWindow();
            if (window != null) {
                // 设置窗口的属性以全屏显示
                window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                window.setBackgroundDrawableResource(android.R.color.transparent);
            }
        });

        LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.dialog_img_item, null);
        ImageView tvClose = v.findViewById(R.id.tvClose);
        CustomImageView imgYu1 = v.findViewById(R.id.imgYu1);
        dialog.setCanceledOnTouchOutside(true);//点击屏幕不消失

        if (!dialog.isShowing()) {//此时提示框未显示
            dialog.show();
        }
        //自定义的东西
        dialog.getWindow().setContentView(v);

        Glide.with(mContext).load(milepostStr).error(R.mipmap.icon_error).into(imgYu1);

        tvClose.setOnClickListener(v1 -> dialog.dismiss());
    }

    private void initClick() {
        findViewById(R.id.tvQie).setOnClickListener(v -> {
            if (StringUtils.isFastClick()) {
                return;
            }
            startActivity(new Intent(mContext, HomeActivity.class));
        });
        lyNoLayout.setOnClickListener(v -> {
            if (StringUtils.isFastClick()) {
                return;
            }
            RPCGetGridPhoto();
        });
    }

    private void upLogInfo(String insertTime) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("time", insertTime);
        jsonObject.put("imei", DeviceIdHelper.getDeviceId(mContext));
        jsonObject.put("loginfo", SPUtils.get(mContext, "benE", ""));
        jsonObject.put("versions", StringUtils.getVerName(mContext));
        jsonObject.put("uname", SPUtils.get(mContext, "userPhone", ""));

        LogUtils.e("TAG", "jsonObject--->" + jsonObject.toString());

        HttpClient.getInstance().post(HttpClient.httpUrl + CommonHttpConsts.upLogInfo, "upLogInfo").upJson(jsonObject.toString()).execute(new HttpCallbackData() {

            @Override
            public void onSuccess(int code, String msg, String info) {
                LogUtils.e("TAG", "info:" + info);
                if (code == 200) {
                    SPUtils.put(mContext, "benE", "");
                    SPUtils.put(mContext, "benS", "");
                }
            }
        });
    }

    //系统升级
    private IndicatorProgressBar mProgress;
    private RelativeLayout rl_softu;
    private LinearLayout lyDialog;
    private TextView tvContext;
    private String destfiledir;
    private String downloadurl;
    private String app_name = "";
    private TextView tvDialogCancel, tvDialogConfirm;
    private int isforcedupdate = 0;

    private void upVersions() {
        HttpClient.getInstance().getData(CommonHttpConsts.upVersion, "upVersion").params("version", StringUtils.getVerName(mContext)).params("railway", "wangge").execute(new HttpCallbackData() {

            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onSuccess(int code, String msg, String info) {
                LogUtils.e("TAG", "info:" + info);
                if (code == 200 && !StringUtils.isEmpty(info)) {
                    String string = StringUtils.decompressForGzip(info);
                    Map dataMap = JSON.parseObject(string, Map.class);
                    LogUtils.e("TAG", dataMap.toString());
                    if (!dataMap.isEmpty()) {
                        lyDialog.setVisibility(View.VISIBLE);
                        tvTakePhoto.setVisibility(View.GONE);
                        downloadurl = dataMap.get("url") + "";
                        app_name = dataMap.get("name") + "";
                        tvContext.setText(dataMap.get("content") + "");
                        String isfo = dataMap.get("force") + "";
                        if (!StringUtils.isEmpty(isfo)) {
                            isforcedupdate = Integer.valueOf(isfo);
                        }
                        if (isforcedupdate == 1) {
                            tvDialogCancel.setVisibility(View.GONE);
                        } else {
                            tvDialogCancel.setVisibility(View.VISIBLE);
                        }
                    }
                }
            }

            @Override
            public void onError(Response<JsonBeanData> response) {
                super.onError(response);
                ToastUtil.show(StringUtils.error_context);
            }

            @Override
            public boolean showLoadingDialog() {
                return true;
            }

            @Override
            public Dialog createLoadingDialog() {
                return DialogUitl.loginAuthDialog(mContext);
            }
        });
    }

    private void downloadNewFile() {
        OkGo.<File>get(downloadurl).tag(mContext).execute(new FileCallback(destfiledir, app_name) {
            @Override
            public void onSuccess(Response<File> response) {
                String s = destfiledir + "/" + app_name;
                rl_softu.setVisibility(View.GONE);
                installApk(s);
            }


            @Override
            public void downloadProgress(Progress progress) {
                super.downloadProgress(progress);
                LogUtils.e("TAG", "下载进度：" + (int) (progress.fraction * 100));
                mProgress.setProgress((int) (progress.fraction * 100));
            }

            @Override
            public void onError(Response<File> response) {
                super.onError(response);
                runOnUiThread(() -> {
                    rl_softu.setVisibility(View.GONE);
                    ToastUtil.show("网络中断，请稍后再试！");
                });
            }
        });
    }

    /**
     * 安装apk
     */
    public void installApk(String apkPath) {
        if (TextUtils.isEmpty(apkPath)) {
            ToastUtil.show("更新失败！未找到安装包");
            return;
        }

        LogUtils.e("TAG", "开始执行安装: " + apkPath);
        File apkFile = new File(apkPath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            LogUtils.e("TAG", "版本大于 N ，开始使用 fileProvider 进行安装");
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(mContext, "com.davy.gridpoint.fileprovider", apkFile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            mContext.startActivity(intent);
        } else {
            LogUtils.e("TAG", "正常进行安装");
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
            mContext.startActivity(intent);
        }
    }

    private static final int REQUEST_LOCATION_PERMISSION_CODE = 1;
    protected LocationManager locationManager;
    public static String mLongitude, mLatitude, mAltitude;
    protected DecimalFormat decimalFormat;
    protected DecimalFormat decimalFormat2;

    private void initLocation() {
        if (locationManager != null) {
            locationManager = null;
        }
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        //获取所有可用的位置提供器
        List<String> providers = locationManager.getProviders(true);
        String locationProvider = "";
        if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
            //如果是Network
            locationProvider = LocationManager.NETWORK_PROVIDER;
        }
        if (providers.contains(LocationManager.GPS_PROVIDER)) {
            //如果是GPS
            locationProvider = LocationManager.GPS_PROVIDER;
        }
        LogUtils.v("TAG", "有权限，开始吧" + locationProvider);
        // 检查权限和服务是否可用
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            if (ActivityCompat.checkSelfPermission(DavyApp.getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                LogUtils.v("TAG", "有没有权限");
                return;
            }
            //LocationManager.NETWORK_PROVIDER  网络
            //LocationManager.GPS_PROVIDER  GPS
            //locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000, 0, locationListener);
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 1, locationListener);
        } else {
            LogUtils.v("TAG", "GPS is disabled");
        }
    }

    LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            // 使用经纬度
            mLongitude = decimalFormat.format(location.getLongitude());
            mLatitude = decimalFormat.format(location.getLatitude());
            mAltitude = decimalFormat2.format(location.getAltitude());

            LogUtils.v("TAG", "经纬度：" + mLongitude + " " + mLatitude + " " + mAltitude);
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            LogUtils.v("TAG", "onStatusChanged：" + provider);
        }

        @Override
        public void onProviderEnabled(String provider) {
            // 用户启用GPS时调用
            LogUtils.v("TAG", "onProviderEnabled：" + provider);
        }

        @Override
        public void onProviderDisabled(String provider) {
            // 用户禁用GPS时调用
            LogUtils.v("TAG", "onProviderDisabled：" + provider);
        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_LOCATION_PERMISSION_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限被授予，可以进行位置相关的操作
                initLocation();
            } else {
                // 权限被拒绝，可以提示用户手动开启权限或进行其他处理
                ToastUtil.show("定位权限授权失败");
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogUtils.e("TAG", "onDestroy");
        // 1. 移除位置监听器
        if (locationManager != null && locationListener != null) {
            try {
                locationManager.removeUpdates(locationListener);
            } catch (SecurityException e) {
                LogUtils.e("TAG", "Permission revoked：" + e);
            }
        }
        // 2. 解除系统服务绑定
        locationManager = null;
        // 3. 释放监听器引用
        locationListener = null;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                ToastUtil.show("再按一次退出程序");
                mExitTime = System.currentTimeMillis();
            } else {
                ScreenManager.getScreenManager().exit();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
